#!/bin/bash
script_path="$( cd "$(dirname "$0")" ; pwd -P )"
app_path="${script_path}/../src"
remote_port="22118"
DDK_BIN="${DDK_HOME}/uihost/bin"
atlas_target="AtlasDK"



# ************************check ip****************************************
# Description:  check ip valid or not
# $1: ip
# ************************************************************************

function check_ip_addr()
{
    ip_addr=$1
    echo ${ip_addr} | grep "^[0-9]\{1,3\}\.\([0-9]\{1,3\}\.\)\{2\}[0-9]\{1,3\}$" > /dev/null
    if [ $? -ne 0 ]
    then
        return 1
    fi

    for num in `echo ${ip_addr} | sed "s/./ /g"`
    do
        if [ $num -gt 255 ] || [ $num -lt 0 ]
        then
            return 1
        fi
   done
   return 0
}


check_param_configure()
{
    remote_host=`cat ${app_path}/param_configure.conf | grep "remote_host" | awk -F'[ =]+' '{print $2}'`
    if [[ ${remote_host} = "" ]];then
        echo "please check your param_configure.conf to make sure that parameters remote_host must have a value"
    fi

    #get and check format of remost_host ip
    check_ip_addr ${remote_host}
    if [ $? -ne 0 ];then
		return 1
    fi

    ${DDK_BIN}/IDE-daemon-client --host ${remote_host}:${remote_port} --hostcmd "rm -rf ~/HIAI_DATANDMODELSET/workspace_mind_studio/resource/"
    if [ $? -ne 0 ];then
        echo "ERROR: Failed to rm -rf ~/HIAI_DATANDMODELSET/workspace_mind_studio/resource/"
        return 1
    fi
}


function build_common()
{
    echo "build common lib..."
    if [ ! -d "${HOME}/ascend_ddk" ];then
        mkdir $HOME/ascend_ddk
        if [[ $? -ne 0 ]];then
            echo "ERROR: Execute mkdir command failed, Please check your environment"
            return 1
        fi
    fi
    bash ${script_path}/build_ezdvpp.sh ${atlas_target}
    if [ $? -ne 0 ];then
        echo "ERROR: Failed to deploy ezdvpp"
        return 1
    fi
    return 0
}

function main()
{   
    echo "Modify param information in graph.config..."
    check_param_configure
    if [ $? -ne 0 ];then
        return 1
    fi

    build_common
    if [ $? -ne 0 ];then
        echo "ERROR: Failed to deploy common lib"
        return 1
    fi

	echo "Modify param information in graph.config..."
	for om_name in $(find ${script_path}/ -name "*.om");do
        om_name=$(basename ${om_name})
        if [ "mobilenetssd" != ${om_name%.*} ];then  
            continue
        fi
        cp ${script_path}/graph.template ${app_path}/graph.config
        sed -i "s#\${MODEL_PATH}#../../script/${om_name}#g"  ${app_path}/graph.config
        if [ $? != 0 ];then
            echo "gengrate graph.config error !"
            return 1
        fi 
        return 0
    done

    echo "please push model file in sample-objectdetection/script"
    return 1
}
main

